package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.ArticleFeign;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImp implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private WmSensitiveMapper sensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;

    @Override
    @Async
    @GlobalTransactional
    public void autoScanWmNews(Integer articleId) throws Exception {
        //根据id查询文章数据
        WmNews wmNews = wmNewsMapper.selectById(articleId);
        //判断文章是否被删除，如被删除就抛出异常
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //只有文章状态为待审核时，才需要走自动审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //从文章中解析得到文章的文本内容和图片内容
            Map<String, Object> data = handleTextAndImages(wmNews);

            //自定义敏感词审核
            Boolean flag = handleSensitiveScan(data.get("text").toString(),wmNews);
            if (!flag){//取反 如果失败直接返回
                return;
            }

            //把文本内容上传到阿里云进行审核，审核失败直接返回，成功就继续审核
             flag = handleTextScan(data.get("text").toString(),wmNews);
            if (!flag){//取反 如果失败直接返回
                return;
            }
            //把图片上传到阿里云进行审核，审核失败直接返回，成功就继续审核
            flag = handleImageScan((List<String>) data.get("images"),wmNews);
            if (!flag){//取反 如果失败直接返回
                return;
            }
            //把自媒体文章数据同步到app端
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)){
                throw new CustomException(AppHttpCodeEnum.TRANS_DATA_FAIL);
            }
            //修改自媒体文章状态为9
            wmNews.setArticleId(Long.parseLong(responseResult.getData().toString()));
            updateWmNews(wmNews,(short) 9,"审核通过");
        }

    }

    /**
     * 自定义敏感词的审核
     * @param text
     * @param wmNews
     * @return
     */
    private Boolean handleSensitiveScan(String text, WmNews wmNews) {
        Boolean flag = Boolean.TRUE;
        //查询所有敏感词
        List<WmSensitive> sensitives = sensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitivesList = sensitives.stream().map(item -> item.getSensitives()).collect(Collectors.toList());
        //初始化DFA敏感词库
        SensitiveWordUtil.initMap(sensitivesList);
        //是否有敏感词 如果有就更新审核状态为2
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if (map != null && map.size() > 0){
            updateWmNews(wmNews,(short) 2,"文本中存在自定义敏感词"+ map);
            flag = Boolean.FALSE;
        }
        //返回审核结果

        return flag;
    }

    /**
     * 同步数据到文章微服务
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
       /* ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);


        //如果id不为空一定能查到用户
        //补全作者信息
        if (wmNews.getUserId() != null){
            articleDto.setAuthorId(wmNews.getUserId());
            WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
            articleDto.setAuthorName(wmUser.getName());
        }
        //补全频道信息
        if (wmNews.getChannelId() != null){
            WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
            articleDto.setChannelName(wmChannel.getName());
        }
        //设置文章id
        if (wmNews.getArticleId() != null){
            articleDto.setId(wmNews.getArticleId());
        }
        //文章布局
        articleDto.setLayout(wmNews.getType());
        //创建时间
        articleDto.setCreatedTime(new Date());*/

        //创建构造者dto
        ArticleDtoBuilder builder = new ArticleDtoBuilder(wmNews,wmUserMapper,wmChannelMapper);
        ArticleDto articleDto = builder.buildBeanCopy()
                .buildAuthor()
                .buildChannel()
                .buildBasic()
                .build();
        //发起feign请求
        ResponseResult responseResult = articleFeign.saveArticle(articleDto);
        return responseResult;
    }

    /**
     * 阿里云图片审核
     * @param images
     * @param wmNews
     * @return
     */
    private Boolean handleImageScan(List<String> images, WmNews wmNews) throws Exception {
        Boolean flag = Boolean.TRUE;
        if (images == null && images.size() == 0 ){
            return flag;
        }
        //下载前对图片去重
        images = images.stream().distinct().collect(Collectors.toList());
        //下载图片
        List<byte[]> imageList = new ArrayList<>(images.size());
        for (String url : images) {
            byte[] bytes = fileStorageService.downLoadFile(url);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            BufferedImage image = ImageIO.read(inputStream);//图片构建工具
            //审核图片文本内容
            String result = tess4jClient.doOCR(image);
            //传入图片文本识别
            flag = handleSensitiveScan(result, wmNews);
            if (!flag){
                return flag;
            }

            imageList.add(bytes);
        }

        Map map = greenImageScan.imageScan(imageList);
        if (map != null){
            if (map.get("suggestion").equals("block")){//审核失败
                flag = Boolean.FALSE;
                //更新状态与失败原因
                updateWmNews(wmNews,(short) 2,"图片中存在违规内容");
            }else if (map.get("suggestion").equals("review")){
                flag = Boolean.FALSE;
                //更新状态与失败原因
                updateWmNews(wmNews,(short) 3,"图片中存在未知内容，需要人工审核");
            }else {
                flag = Boolean.FALSE;
            }
        }
        return flag;
    }

    /**
     * 阿里云文本审核
     * @param text
     * @param wmNews
     * @return
     */
    private Boolean handleTextScan(String text, WmNews wmNews) throws Exception {
        Boolean flag = Boolean.TRUE;
        if (StringUtils.isEmpty(text)){
            return flag;
        }
        Map map = greenTextScan.greeTextScan(text);
        if (map != null){
            if (map.get("suggestion").equals("block")){//审核失败
                flag = Boolean.FALSE;
                //更新状态与失败原因
                updateWmNews(wmNews,(short) 2,"文本中存在违规内容");
            }else if (map.get("suggestion").equals("review")){
                flag = Boolean.FALSE;
                //更新状态与失败原因
                updateWmNews(wmNews,(short) 3,"文本中存在未知内容，需要人工审核");
            }
        }
        return flag;
    }

    /**
     * 更新文章审核状态和原因
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        //更新
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从文章中抽取文本内容与图片内容
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //收集文本
        StringBuilder sb = new StringBuilder();
        //收集图片
        List<String> images = new ArrayList<>();
        //处理文本内容
        if (StringUtils.isNotEmpty(wmNews.getContent())) {
            List<Map> list = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : list) {
                if ("text".equals(map.get("type").toString())) {
                    sb.append(map.get("value").toString());
                } else {
                    images.add(map.get("value").toString());
                }
            }
        }
        //处理封面
        if (StringUtils.isNotEmpty(wmNews.getImages())){
            images.addAll(Arrays.asList(wmNews.getImages().split(",")));
        }
        //处理标题
        sb.append("-").append(wmNews.getTitle());

        Map<String, Object> map = new HashMap<>();
        map.put("text",sb.toString());
        map.put("images",images);

        return map;
    }
}
